<template>
	<view class="addressForm">
		<u--form labelPosition="top" :model="addressForm" :rules="addressRules" labelWidth="80" ref="uForm">
			<u-form-item label="姓名" prop="username">
				<u--input v-model="addressForm.username" placeholder="请输入姓名">
				</u--input>
			</u-form-item>
			<u-form-item label="联系电话" prop="mobile">
				<u--input v-model="addressForm.mobile" placeholder="请输入电话">
				</u--input>
			</u-form-item>
			<u-form-item label="选择地区">
				<uni-data-picker v-model="addressForm.areaCode" placeholder="请选择地址" popup-title="请选择所在地区"
					collection="opendb-city-china" field="code as value, name as text" orderby="value asc"
					:step-searh="true" self-field="code" parent-field="parent_code" @change="PickerChange">
				</uni-data-picker>
			</u-form-item>
			<u-form-item label="详细地址" prop="address">
				<u--input v-model="addressForm.address" placeholder="请输入详细地址">
				</u--input>
			</u-form-item>
			<u-form-item label="设为默认">
				<u-switch v-model="addressForm.selected" inactiveColor="#eee"></u-switch>
			</u-form-item>
			<u-form-item>
			</u-form-item>

			<button type="primary" @click="onSubmit">提交</button>

		</u--form>
	</view>
</template>

<script>
	const addressCloudObj = uniCloud.importObject("wanshop-mall-address")
	let addressId;
	export default {
		data() {
			return {
				addressName: {
					locationName: "",
					locationAddress: ""
				},

				addressForm: {
					username: "",
					mobile: "",
					address: "",
					selected: false,
					areaCode: "",
					area_name: "",
					user_id: "",
					creatTime: ""
				},
				addressRules: {
					username: [{
						required: true,
						message: '姓名是必填的',
						trigger: ['blur', 'change'],
					}, {
						min: 2,
						max: 8,
						message: '长度在6-8个字符之间'
					}],
					mobile: [{
							required: true,
							message: '电话是必填的',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					address: [{
						required: true,
						message: '地址是必填的',
						trigger: ['blur', 'change'],
					}, {
						min: 4,
						max: 20,
						message: '长度在6-20个字符之间'
					}],

				}
			};
		},
		onLoad(e) {
			addressId = e?.id ?? null;
			if (addressId) this.getAddressOne();
		},
		methods: {
			authVerification () {
			  uni.getSetting({
			    success: (res) => {
			      if (res.authSetting['scope.userLocation']) { /* 用户授权成功时走这里 */
			        this.handerChooseLocation()
			      } else if (res.authSetting['scope.userLocation'] === undefined) { /* 用户未授权时走这里 */
			        console.log('没有授权')
			        this.handleOpenSetting()
			      } else { /* 用户拒绝了授权后走这里 */
			        console.log('拒绝了授权 false')
			        this.handleOpenSetting()
			      }
			    },
			  })
			},
			handerChooseLocation (latitude, longitude) {
			  uni.chooseLocation({
			    latitude: latitude || '',
			    longitude: longitude || '', 
			    success: (res) => {
			      console.log('wx.chooseLocation res=', res)
			      uni.setStorageSync('currentLocation', res)
			    },
			    fail: function (err) {
			      console.log('取消按钮', err)
			    }
			  })
			},
			handleOpenSetting () {
			  wx.openSetting({
			    success: (res) => {
			      console.log('定位 openSetting', res)
			      if (res.authSetting["scope.userLocation"]) {
			        this.handerChooseLocation()
			      }
			    }
			  })
			},
			PickerChange(e) {
				console.log(e);
				let area_name = e.detail.value.map(item => {
					return item.text
				})
				this.addressForm.area_name = area_name.join("")
			},
			onSubmit() {
				this.$refs.uForm.validate().then(async res => {
					uni.$u.toast('校验通过');

					let title;

					if (this.addressForm._id) {
						let resData = await addressCloudObj.updateOne(this.addressForm);
						title = "修改成功";
					} else {
						let resData = await addressCloudObj.add(this.addressForm);
						title = "添加成功";
					}

					uni.showToast({
						title,
						mask: true
					});

					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}).catch(errors => {
					// 错误处理
					uni.$u.toast('校验失败');
					console.error('验证错误:', errors);
				});
			},
			// 获取一条地址信息
			async getAddressOne() {
				let res = await addressCloudObj.getOne(addressId)
				console.log(res);
				this.addressForm = res.data[0]
			}
		}
	}
</script>

<style lang="scss">
	.addressForm {
		padding: 30rpx;
	}
</style>